<template>
  <Card id="fixedCostTable">
    <Row>
      <Col span="4">
      <div class="btns" style="margin-bottom: 15px;">
        <Button icon="ios-add" type="primary" @click="addCost">新增年度</Button>
        <Button icon="ios-refresh" @click="refresh">刷新</Button>
      </div>
      <Alert show-icon>
        当前选择：
        <span class="select-title">{{ selectTitle }}</span>
      </Alert>
      <div class="tree-bar">
        <Tree ref="tree" :data="treeKeyData" @on-select-change="selectTree"></Tree>
        <Spin v-if="spinShow" fix size="large"></Spin>
      </div>
      </Col>
      <Col span="18">
      <div>
        <h1 style="text-align: center;margin-bottom: 15px;">{{ tableTitle }}</h1>
      </div>
      <vxe-toolbar>
        <template v-slot:buttons>
          <vxe-button status="success" @click="saveEvent">保存</vxe-button>
          <vxe-button @click="refreshEvent">刷新</vxe-button>
          <vxe-button status="info" style="float: right;" @click="openFullModal">成本项目设置</vxe-button>
        </template>
      </vxe-toolbar>
      <vxe-grid
        ref="xTable"
        :cell-style="cellStyle"
        :loading="loading"
        v-bind="gridOptions"
        @edit-disabled="editDisabledEvent"
      ></vxe-grid>
      </Col>
    </Row>
    <Modal v-model="modal11" :mask-closable="false" title="成本项目设置" width="700">
      <Card id="fixedCostTree">
        <a-button :disabled="addDisabled" icon="plus-circle" type="primary" @click="addChild">增加子节点</a-button>
        <a-button :disabled="editDisabled" @click="showModal">编辑</a-button>
        <a-button :disabled="deleteDisabled" type="danger" @click="confirmDelete">删除</a-button>
        <a-divider/>
        <a-spin :spinning="spinning" tip="加载中...">
          <a-tree
            :default-expand-all="defaultExpandAll"
            :show-line="showLine"
            :tree-data="gData"
            class="draggable-tree"
            draggable
            @dragend="onDragEnd"
            @drop="onDrop"
            @select="onSelect"
          ></a-tree>
        </a-spin>
      </Card>
      <div slot="footer">
        <Button type="primary" @click="refreshTree">确定</Button>
      </div>
    </Modal>
    <Modal v-model="addModal" title="增加子节点">
      <Input v-model="addTitle" clearable placeholder="请输入名称"/>
      <div slot="footer">
        <a-button key="back" @click="handleAdd">取消</a-button>
        <a-button key="submit" :loading="addLoading" type="primary" @click="handleAddOk">保存</a-button>
      </div>
    </Modal>
    <Modal v-model="editModal" class-name="vertical-center-modal" title="修改名称">
      <Input v-model="editTitle" clearable placeholder="请输入名称"/>
      <div slot="footer">
        <a-button key="back" @click="handleEdit">取消</a-button>
        <a-button key="submit" :loading="editLoading" type="primary" @click="handleEditOk">保存</a-button>
      </div>
    </Modal>
    <Modal v-model="addModalCost" title="新增年度">
      <Form ref="Form" :label-width="80" :model="Form" :rules="FormValidate">
        <FormItem label="年度：" prop="title">
          <Input v-model="Form.title" number placeholder="请输入年度(例如: 2021)"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="handleAddCost">取消</Button>
        <Button :loading="addLoadingCost" type="primary" @click="handleAddCostOk">保存</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  addCostKey,
  addFixedCostTree,
  destroyFixedCostTree,
  editFixedCostTree,
  fixedCostTable,
  fixedCostTree,
  getTreeKeyList,
  updateFixedCostTable,
  updateFixedCostTree
} from '../../api/fixedCost'

export default {
  data() {
    return {
      Form: {
        title: '',
      },
      FormValidate: {
        // 表单验证规则
        title: [{required: true, type: 'number', message: '年份不能为空', trigger: 'blur'}],
      },
      treeKeyData: [],
      tableTitle: '城市公共汽车客运成本表',
      selectTitle: '',
      gridOptions: {
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        highlightCell: true,
        data: [],
        size: 'mini',
        id: 'full_edit_1',
        rowId: 'id',
        customConfig: {
          storage: true,
          checkMethod: this.checkColumnMethod
        },
        columns: [
          {field: 'type', title: '项目', minWidth: 200,},
          {
            field: 'amount',
            title: '金额',
            minWidth: 200,
            align: 'right',
            editRender: {name: '$input', props: {type: 'string'}}
          },
          {
            field: 'note',
            title: '备注',
            minWidth: 200,
            align: 'right',
            editRender: {name: '$input', props: {type: 'string'}}
          }
        ],
        editConfig: {
          trigger: 'click',
          mode: 'cell',
          showStatus: true,
          activeMethod: this.activeRowMethod
        }
      },
      loading: false,
      modal11: false,
      defaultExpandAll: true,
      addModal: false,
      addModalCost: false,
      addLoadingCost: false,
      editModal: false,
      addDisabled: true,
      editDisabled: true,
      deleteDisabled: true,
      editLoading: false,
      addLoading: false,
      gData: [],
      showLine: true,
      addTitle: '',
      editTitle: '',
      editNode: null,
      spinning: false,
      spinShow: false,
      addParentNode: ''
    }
  },
  mounted() {
    this.getTreeKeyData()
  },
  methods: {
    addCost() {
      this.addModalCost = true
    },
    handleAddCost() {
      this.Form.title = ''
      this.addModalCost = false
    },
    handleAddCostOk() {
      this.addLoadingCost = true
      this.$refs.Form.validate(valid => {
        if (valid) {
          addCostKey(this.Form).then(res => {
            this.addLoadingCost = false
            if (res.data) {
              this.$Message.success(res.message)
              this.Form.title = ''
              this.addModalCost = false
              this.getTreeKeyData()
            }
          })
        }
      })
    },
    getTreeKeyData() {
      this.spinShow = true
      getTreeKeyList().then(res => {
        this.spinShow = false
        if (res.data) {
          this.selectTitle = res.data.selectYear
          this.treeKeyData = res.data.data
          this.init(this.selectTitle)
        }
      })
    },
    refresh() {
      this.selectTitle = ''
      this.getTreeKeyData()
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (const attr in v[0]) {
          if (v[0][attr] === null) {
            v[0][attr] = ''
          }
        }
        const str = JSON.stringify(v[0])
        const data = JSON.parse(str)
        this.selectTitle = data.title
        this.init(data.title)
      }
    },
    confirmDelete() {
      this.$Modal.confirm({
        title: '确认删除【 ' + this.editTitle + ' 】吗？',
        loading: true,
        onOk: () => {
          destroyFixedCostTree({time: this.selectTitle, ids: this.editNode}).then(res => {
            if (res.data) {
              this.$Modal.remove()
              this.$Message.info('删除成功')
              this.getTree(this.selectTitle)
            }
          })
        },
        onCancel: () => {
        }
      })
    },
    activeRowMethod({row, rowIndex, column}) {
      return !(row.hasChildren && column.property === 'amount')
    },
    editDisabledEvent({row, column}) {
      this.$message.info('保存之后将自动计算')
    },
    init(v) {
      this.tableTitle = '城市公共汽车客运成本表（' + v + '年)'
      this.loading = true
      fixedCostTable({time: v}).then(res => {
        this.gridOptions.data = res.data
        this.loading = false
      })
    },
    getTree(v) {
      this.spinning = true
      fixedCostTree({time: v}).then(res => {
        this.defaultExpandAll = true
        this.gData = res.data
        this.spinning = false
      })
    },
    saveEvent() {
      const {
        insertRecords,
        removeRecords,
        updateRecords
      } = this.$refs.xTable.getRecordset()
      if (updateRecords.length === 0) {
        this.$message.info('未编辑数据')
      } else {
        this.loading = true
        updateFixedCostTable({time: this.selectTitle, paramsData: updateRecords}).then(res => {
          this.init(this.selectTitle)
        })
      }
    },
    cellStyle({row, rowIndex, column, columnIndex}) {
      if (column.property === 'type') {
        if (row.node === 1) {
          return {
            color: '#515a6e',
            fontWeight: 'bold'
          }
        }
      }
    },
    refreshEvent() {
      this.init(this.selectTitle)
    },
    openFullModal() {
      this.modal11 = true
      this.getTree(this.selectTitle)
    },
    onDrop(info) {
      const dropKey = info.node.eventKey
      const dragKey = info.dragNode.eventKey
      const dropPos = info.node.pos.split('-')
      const dropPosition =
        info.dropPosition - Number(dropPos[dropPos.length - 1])
      const loop = (data, key, callback) => {
        data.forEach((item, index, arr) => {
          if (item.key === key) {
            return callback(item, index, arr)
          }
          if (item.children) {
            return loop(item.children, key, callback)
          }
        })
      }
      const data = [...this.gData]

      // Find dragObject
      let dragObj
      loop(data, dragKey, (item, index, arr) => {
        arr.splice(index, 1)
        dragObj = item
      })
      if (!info.dropToGap) {
        // Drop on the content
        loop(data, dropKey, item => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.push(dragObj)
        })
      } else if (
        (info.node.children || []).length > 0 && // Has children
        info.node.expanded && // Is expanded
        dropPosition === 1 // On the bottom gap
      ) {
        loop(data, dropKey, item => {
          item.children = item.children || []
          // where to insert 示例添加到尾部，可以是随意位置
          item.children.unshift(dragObj)
        })
      } else {
        let ar
        let i
        loop(data, dropKey, (item, index, arr) => {
          ar = arr
          i = index
        })
        if (dropPosition === -1) {
          ar.splice(i, 0, dragObj)
        } else {
          ar.splice(i + 1, 0, dragObj)
        }
      }
      this.gData = data
    },
    onDragEnd() {
      this.spinning = true
      updateFixedCostTree({time: this.selectTitle, data: this.gData}).then(res => {
        if (res.data) {
          this.$message.success('排序成功')
        }
        this.getTree(this.selectTitle)
      })
    },
    onSelect(node, e) {
      this.addDisabled = this.editDisabled = this.deleteDisabled = !e.selected
      this.editTitle = e.node.title
      this.editNode = e.node.eventKey
      this.addParentNode = e.node.eventKey
    },
    showModal() {
      this.editLoading = false
      this.editModal = true
    },
    addChild() {
      this.addLoading = false
      this.addModal = true
      this.addTitle = ''
    },
    handleEdit() {
      this.editTitle = ''
      this.editModal = false
    },
    handleAdd() {
      this.addTitle = ''
      this.addModal = false
    },
    handleEditOk() {
      this.editLoading = true
      editFixedCostTree({time: this.selectTitle, key: this.editNode, title: this.editTitle}).then(
        res => {
          this.editLoading = false
          this.editModal = false
          if (res.data) {
            this.$message.success('修改成功')
            this.getTree(this.selectTitle)
          } else {
            this.$message.error('修改失败')
          }
        }
      )
    },
    handleAddOk() {
      this.addLoading = true
      addFixedCostTree({
        parentKey: this.addParentNode,
        title: this.addTitle,
        time: this.selectTitle
      }).then(res => {
        this.addLoading = false
        this.addModal = false
        if (res.data) {
          this.$message.success('修改成功')
          this.getTree(this.selectTitle)
        } else {
          this.$message.error('修改失败')
        }
      })
    },
    refreshTree() {
      this.modal11 = false
      this.init(this.selectTitle)
    },
  }
}
</script>
<style>
#fixedCostTable .vxe-grid,
#fixedCostTable .vxe-toolbar {
  width: 90%;
  margin-right: auto;
  margin-left: auto;
}

.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;
}

.vertical-center-modal .ivu-modal {
  top: 0;
}
</style>
